<template>
	<div>
		<so-header :title="title"></so-header>
		<div class="layim-chat-main" id="dcontent">
			<ul id="talks-content">
				
			</ul>
		</div>
		<div class="talkButton">
			<div class="button" @click="startRecognizeEnglish()">懒读</div>
		</div>
		<audio autoplay="true" id="audio-play" src=""></audio>
	</div>
</template>
<script>
	import {MessageBox }from 'mint-ui'
	import soHeader from 'components/header'
	import soFooter from 'components/footer'
	export default {
		components: {
			soHeader,
			soFooter
		},
		data() {
			return {
				title: "朗读",
				url : 'getOneTextById/',
				urlSpeech : this.GLOBAL.ldyPort+'read?text=',
				talks : null,
				dcontent : null,
				audioplay : null,
				xhr: null,
				textContent : [], //文章的所有句子
				textOne : '', //句子内容
				textIndex : 0, // 文章的索引
				
			}
		},
		methods: {
			http(){
				this.$axios.get(this.url)
				.then((response) =>{
					console.log(response.data)
					if(response.data!='undefined'||response.data!=''){
	                	this.textContent=response.data.split(/[,.;?!，。；？！]+/);
	                	this.textOne=this.textContent[this.textIndex];
	                	this.addTalk(this.textOne,0);
	               }
				});
			},
			getText() {
				console.log("ASAAA")
				this.xhr = new XMLHttpRequest();  // XMLHttpRequest 对象  
                this.xhr.open("get", 'http://47.106.98.87:8083/'+this.url, true); //get方式，url为服务器请求地址，true 该参数规定请求是否异步处理。  
                //xhr.setRequestHeader('reportRecordId',reportRecordId);
                //xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】
                this.xhr.onload = uploadComplete; //请求完成  
                this.xhr.onerror = uploadFailed; //请求失败  
//              xhr.upload.onloadstart = function(){//上传开始执行方法  
//		            ot = new Date().getTime();   //设置上传开始时间  
//		            oloaded = 0;//设置上传开始时，以上传的文件大小为0  
//              };	
                this.xhr.send(null); //开始上传，发送form数据  
			},
			startRecognize() {
				if(plus.os.name=='Android'&&navigator.userAgent.indexOf('StreamApp')>0){
					plus.nativeUI.toast('当前环境暂不支持语音识别插件');
					return;
				}
				var options = {};
				options.engine = 'iFly';
				//options.punctuation = false;	// 是否需要标点符号 
				console.log( "开始语音识别：" );
				plus.speech.startRecognize( options, function ( s ) {
					//语音识别成功
				}, function ( e ) {
					console.log( "语音识别失败："+e.message );
				} );
			},
			startRecognizeEnglish(){
				if(plus.os.name=='Android'&&navigator.userAgent.indexOf('StreamApp')>0){
					plus.nativeUI.toast('当前环境暂不支持语音识别插件');
					return;
				}
				var options = {};
				
				options.engine = 'iFly';
				options.lang = 'en-us';
				options.timeout=20000;
				options.punctuation = false;
				console.log( "开始语音识别：" );
				var _this=this;
				plus.speech.startRecognize( options, function ( s ) {
					console.log(s);
					console.log(_this.textOne)
					//显示度大于 0.8认为正确
					if(_this.levenshteinStr(s.toLowerCase(),_this.textOne.trim().toLowerCase())>0.8){
					//if(s.toLowerCase()==textOne.trim().toLowerCase()){
						_this.textIndex++;
						_this.textOne=_this.textContent[_this.textIndex];
						if(_this.textOne!='undefined'&&_this.textOne!=''&&_this.textOne!=null){
							_this.addTalk(_this.textOne.trim(),0);
						}
					}else{
						_this.audioplay.src=_this.urlSpeech+'主人,应该这样读.'+_this.textOne;
					}
				}, function ( e ) {
					console.log( "语音识别失败："+e.message );
				} );
			},
			//增加
			addTalk(text,value){
					var li = document.createElement("li");
					li.innerHTML="<div class='layim-chat-text'>"+text+"</div>";
					this.talks.appendChild(li);
					this.dcontent.scrollTop=this.dcontent.scrollHeight;
					this.audioplay.src=this.urlSpeech+text;
			},
			//上传成功相应
			uploadComplete(evt) {  
                //服务断接收完文件返回的结果  
                console.log('回复',typeof evt.target.responseText);
                if(evt.target.responseText!='undefined'||evt.target.responseText!=''){
                	this.textContent=evt.target.responseText.split(/[,.;?!，。；？！]+/);
                	this.textOne=textContent[textIndex];
                	this.addTalk(textOne,0);
                }
               
            },
            //上传失败响应
            uploadFailed(evt) {
				//上传失败
				console.log('请求失败',evt.target.responseText)
           },
           //判断相似度
           levenshteinStr(str1,str2) {
				//去除特殊字符
		        str1 = str1.replace(/[^a-zA-Z0-9 _\u4e00-\u9fa5]+/g, "").trim().toLowerCase();
				str2 = str2.replace(/[^a-zA-Z0-9 _\u4e00-\u9fa5]+/g, "").trim().toLowerCase();
		        //计算两个字符串的长度。
		       	var strArr1=str1.split(" ");
				var strArr2=str2.split(" ");
				
		        var len1 = strArr1.length;
		        var len2 = strArr2.length;
		        //建立上面说的数组，比字符长度大一个空间
		        var dif = new Array();         //先声明一维
			       for(var i=0;i<len1 + 1;i++){          //一维长度为5
			          dif[i]=new Array(i);    //在声明二维
			          for(var j=0;j<len2 + 1;j++){  
			              //二维长度为5
			             dif[i][j]=i;
			          }   
		       }
		        //赋初值，步骤B。
		        for (var a = 0; a <= len1; a++) {
		            dif[a][0] = a;
		        }
		        for (var a = 0; a <= len2; a++) {
		            dif[0][a] = a;
		        }
		        //计算两个字符是否一样，计算左上的值
		        var temp;
		        for (var i = 1; i <= len1; i++) {
		            for (var j = 1; j <= len2; j++) {
		                if (strArr1[i - 1] == strArr2[j - 1]) {
		                    temp = 0;
		                } else {
		                    temp = 1;
		                }
		                //取三个值中最小的
		                dif[i][j] = Math.min(dif[i - 1][j - 1] + temp, dif[i][j - 1] + 1,
		                        dif[i - 1][j] + 1);
		            }
		        }
		        console.log("字符串\""+str1+"\"与\""+str2+"\"的比较");
		        //取数组右下角的值，同样不同位置代表不同字符串的比较
		        console.log("差异步骤："+dif[len1][len2]);
		        //计算相似度
		        var similarity =1 - parseFloat(dif[len1][len2] / Math.max(len1, len2));
		        console.log("相似度："+similarity);
		        return similarity;
		    }
		},
		mounted(){
			this.talks=document.getElementById('talks-content');
			this.dcontent=document.getElementById('dcontent');
			this.audioplay=document.getElementById('audio-play');
			//this.getText();
			console.log("read",this.GLOBAL.textContent)
			this.textContent=this.GLOBAL.textContent.split(/[,.;?!，。；？！]+/);
			this.textOne=this.textContent[this.textIndex];
	        this.addTalk(this.textOne,0);
			//this.http();
			
		}
	}
</script>
<style lang="less">
	.talkButton{
		position: fixed;
		bottom: 5px;
		left: 0;
		text-align: center;
		width: 100%;
	}			
	.layim-chat-main {
	    height: 90%;
	    padding: 10px;
	    overflow-x: hidden;
	    overflow-y: auto;
	}
	.layim-chat-main ul li {
	    position: relative;
	    font-size: 0;
	    padding-left: 0px;
	    padding-right: 10px;
	    min-height: 68px;
	}
	.layim-chat-main ul .layim-chat-mine {
	    text-align: right;
	    padding-left: 0;
	}
	.layim-chat-text {
	    display: inline-block;
	    vertical-align: top;
	    font-size: 14px;
	}
	.layim-chat-mine .layim-chat-text {
	    margin-left: 0;
	    text-align: left;
	    background-color: #5FB878;
	    color: #fff;
	}
	.layim-chat-text {
	    position: relative;
	    line-height: 22px;
	    margin-top: 25px;
	    padding: 8px 15px;
	    background-color: #e2e2e2;
	    border-radius: 3px;
	    color: #333;
	    word-break: break-all;
	    max-width: 462px\9;
	}
	.layim-chat-text:after {
	    content: '';
	    position: absolute;
	    left: -10px;
	    top: 13px;
	    width: 0;
	    height: 0;
	    border-style: solid dashed dashed;
	    border-color: #e2e2e2 transparent transparent;
	    overflow: hidden;
	    border-width: 10px;
	}
	.layim-chat-mine .layim-chat-text:after {
	    left: auto;
	    right: -10px;
	    border-top-color: #5FB878;
	}
	.button {
		font-size: 18px;
		font-weight: normal;
		text-decoration: none;
		display: block;
		text-align: center;
		overflow:hidden;
		text-overflow:ellipsis;
		white-space:nowrap;
		color: #FFF;
		background-color: #FFCC33;
		border: 1px solid #ECB100;
		padding: .5em 0em;
		margin: .5em .7em;
		-webkit-border-radius: 5px;
		border-radius: 5px;
	}
	.button:active {
		outline: 0;
	  	-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
		box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
	}
</style>